# -*- coding: utf-8 -*-
from django import forms
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import RequestContext
from django.contrib.formtools.wizard import FormWizard
from getdebt.main.models import Contragent, Firm, Individual, Debt, OPF, Sector, City, Currency, Status
from django.forms.extras.widgets import SelectDateWidget
from getdebt.advice.views import advices
from getdebt.profile.views import userinfo, user_can_add
from django.contrib.auth.decorators import user_passes_test
import datetime

class ShowOnly(forms.Widget):
    """
    Show only the data do NOT have a input field
    """
    input_type = 'hidden'

    def render(self, name, value, attrs=None):
        from django.utils.safestring import mark_safe
        from django.utils.encoding import force_unicode
        if value is None: value = ''
        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            value = force_unicode(value)
            final_attrs['value'] = force_unicode(value)
        return mark_safe(u'<input%s />%s' % (forms.util.flatatt(final_attrs),value))

class VidForm(forms.Form):
    VID_CHOICES = (
        (u'firm', u'Организация'),
        (u'individual', u'Физическое лицо'),
    )
    vid = forms.ChoiceField(choices=VID_CHOICES, label = '* Вид контрагента', widget = forms.RadioSelect({'class':'rb'}))
    class Meta:
		verbose_name = 'Выберите вид контрагента'
    class Event:
        event_code = 'vid_contragent'

class VidFormWizard(VidForm):
    debtor = forms.ModelChoiceField(queryset=Contragent.objects.all(), label = '* Город', widget = forms.Select({'class':'opf'}),empty_label=None)
    def __init__(self, *args, **kwargs):
        user = kwargs['initial']['user']
        super(VidForm, self).__init__(*args, **kwargs)
        self.fields['debtor'].queryset = Contragent.objects.filter(user=user, status__code='debtor')
    class Meta(VidForm.Meta):
        fields=('vid','debtor')
        
class YesnoForm(forms.Form):
    YESNO_CHOICES = (
        (u'yes', u'Да'),
        (u'', u'Нет'),
    )
    yesno = forms.ChoiceField(choices=YESNO_CHOICES, label = '* Вы уверены?', widget = forms.RadioSelect({'class':'rb'}))
    class Meta:
        verbose_name = 'Выберите вариант ответа'

class FirmForm(forms.ModelForm):
	opf = forms.ModelChoiceField(queryset=OPF.objects.all().order_by('id'), label = '* Организационно-правовая форма', widget = forms.RadioSelect({'class':'rb'}),empty_label=None)
	sector = forms.ModelChoiceField(queryset=Sector.objects.all().order_by('id'), label = '* Основная отрасль', widget = forms.RadioSelect({'class':'rb'}),empty_label=None)
	city = forms.ModelChoiceField(queryset=City.objects.all().order_by('id'), label = '* Город', widget = forms.Select({'class':'opf'}),empty_label=None)
	class Meta:
		model=Firm
		verbose_name = 'Введите данные организации'
		fields=('opf','name','inn','sector','bankr','city','address', 'tel1','tel2','site','email','contact','post')
	class Event:
		event_code = 'add_firm'
		
class IndividualForm(forms.ModelForm):
	city = forms.ModelChoiceField(queryset=City.objects.all().order_by('id'), label = '* Город', widget = forms.Select({'class':'opf'}),empty_label=None)
	class Meta:
		model=Individual
		verbose_name = 'Введите данные физического лица'
		fields=('ip','fio','inn','city','address', 'tel1','tel2','email','contact')
	class Event:
		event_code = 'add_individual'		

class DebtFormWizard(forms.ModelForm):
	currency = forms.ModelChoiceField(queryset=Currency.objects.all().order_by('id'), label = 'Валюта', widget = forms.Select({'class':'opf'}),empty_label=None)
	date = forms.DateField(label = '* Дата возникновения',initial=datetime.date.today(), widget=SelectDateWidget({'class':'date'}))
	class Meta:
		model=Debt
		verbose_name = 'Введите информацию об обязательстве'
		fields=('date','summa', 'penalty','currency','genesis','state','paid','agree')
	class Event:
		event_code = 'add_debt'		

class DebtForm(DebtFormWizard):
    def __init__(self, *args, **kwargs):
        user = kwargs['user']
        del kwargs['user']
        super(DebtFormWizard, self).__init__(*args, **kwargs)
        self.fields['debtor'].queryset = Contragent.objects.filter(user=user, status__code='debtor')
        self.fields['debtor'].empty_label=None
        self.fields['creditor'].queryset = Contragent.objects.filter(user=user, status__code='creditor')
        self.fields['creditor'].empty_label=None            
    class Meta(DebtFormWizard.Meta):
        fields=('creditor','debtor','date','summa', 'penalty','currency','genesis','state','paid','agree')
            
class AddDebtWizard(FormWizard):
	# ИСПРАВИТЬ!!!!!!!
    @user_passes_test(user_can_add, login_url="/login/")
    def render_template(self, request, form, previous_fields, step, context=None):
        pre=''
        if step in (0,1):
            pre = u'Информация о должнике : '
        if step in (2,3):
            pre = u'Информация о кредиторе : '
        return render_to_response(self.get_template(step), dict(context,
                                                                step_field=self.step_field_name,
                                                                step0=step,
                                                                step=step + 1,
                                                                step_count=self.num_steps(),
                                                                form=form,
                                                                previous_fields=previous_fields,
                                                                advices_list = advices(request, form.Event.event_code)
                                                                ), context_instance=RequestContext(request, processors=[userinfo]))
    
    def process_step(self, request, form, step):
        try:
            vid = form.cleaned_data['vid']
        except:
            vid = None
        else:
            self.form_list.pop(step+1)
        if vid=='firm':
            self.form_list.insert(step+1, FirmForm)
        elif vid=='individual':
            self.form_list.insert(step+1, IndividualForm)     
                   
    def parse_params(self, request, *args, **kwargs):
        self.initial = {0:{'user':request.user}}
        
	def done(self, request, form_list):
		dictionary = {}
		form_data = [form.cleaned_data for form in form_list]
		debtor = form_data[0]['name']
		creditor = form_data[1]['name']
		email = form_data[1]['email']
		tel = form_data[1]['tel1']
		summa = form_data[2]['summa']
		message1 = form_data[2]['genesis']
		message2 = form_data[2]['state']
		message_send = u'Должник: ' + debtor + u'. Сумма долга: ' + str(summa) + u'. Возникновение долга: ' + message1 + u'. Текущее состояние: ' + message2 + u'. Телефон:'+tel
		try:
			send_mail(
				u'Сообщение сервиса долгов, кредитор: %s' % creditor,
				message_send, email,
				['panpro@inbox.ru']
			)
		except:
			dictionary['errorsend']=True
		
		new_debtor = form_list[0].save(commit=False)
		new_debtor.rec_date = datetime.datetime.now()
		new_debtor.status = get_object_or_404(Status, code="debtor")
		try:
			new_debtor.save()
		except:
			dictionary['errorsend']=True
		
		new_cred = form_list[1].save(commit=False)
		new_cred.rec_date = datetime.datetime.now()
		new_cred.status = get_object_or_404(Status, code="debtor")
		try:
			new_cred.save()
		except:
			dictionary['errorsend']=True
		
		new_debt = form_list[2].save(commit=False)
		new_debt.rec_date = datetime.datetime.now()
		new_debt.debtor = new_debtor
		new_debt.creditor = new_cred
		try:
			new_debt.save()
		except:
			dictionary['errorsend']=True
		
		dictionary['form_list'] = form_list
		return render_to_response('forms/done.html', dictionary,
		context_instance=RequestContext(request, processors=[]))
